package com.github.soiff.shadow.autoconfigure;

import com.github.jknack.handlebars.io.ServletContextTemplateLoader;
import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
import org.springframework.web.servlet.view.AbstractUrlBasedView;

import java.io.IOException;

/**
 * Created by Soiff on 2016/05/23.
 *
 * @author : Soiff
 */
public class HandlebarsViewResolver extends AbstractTemplateViewResolver {
    public static final String DEFAULT_CONTENT_TYPE = "text/html;charset=UTF-8";

    public HandlebarsViewResolver() {
        this.setViewClass(HandlebarsView.class);
        this.setContentType(DEFAULT_CONTENT_TYPE);
    }

    public void setPrefix(String prefix) {
        throw new UnsupportedOperationException("Use " + ServletContextTemplateLoader.class.getName() + "#setPrefix");
    }

    public void setSuffix(String suffix) {
        throw new UnsupportedOperationException("Use " + ServletContextTemplateLoader.class.getName() + "#setSuffix");
    }

    protected AbstractUrlBasedView buildView(String viewName) throws Exception {
        return this.configure((HandlebarsView)super.buildView(viewName));
    }

    protected AbstractUrlBasedView configure(HandlebarsView view) throws IOException {
        String url = view.getUrl();
        if(url.startsWith("/")) {
            url = url.substring(1);
        }

        view.setUrl(url);
        return view;
    }

    protected Class<?> requiredViewClass() {
        return HandlebarsView.class;
    }
}
